﻿using System;
using UnityEngine;

public class MainGame : BaseMono
{
	public static MainGame Ins;

	public bool Debug;
	[HideInInspector]
	public int Row;
	[HideInInspector]
	public int Col;

	public bool IsGameEnd = false;

	public static GameInfo GameInfo;

	public static MapGenerate MapGenerate;
	public static AStarGridMgr AStarGridMgr;
	public static PlayerCtrl Player;
	public static EnemyMgr EnemyMgr;

	public int LevelID;
	public LevelInfo CurLevelInfo;

	public override void onAwake()
	{
		Ins = this;
		MyLog.IsShow = Debug;

		//data
		string dataPath = FileDef.FilePath;
		GameInfo = XmlTool.Load<GameInfo>(dataPath);

		//res
		GameRes.Ins.Load();

		MapGenerate = new MapGenerate();
		MapGenerate.Init(MyTrans.position);

		AStarGridMgr = gameObject.TryGetComponent<AStarGridMgr>();
		AStarGridMgr.Init();

		GameObject playerGo = Instantiate(Resources.Load<GameObject>("Player/Prefabs/Player"));
		Player = playerGo.TryGetComponent<PlayerCtrl>();
		Player.transform.SetParent(GameObject.FindWithTag("Root").transform);
		Player.Init();
		Player.OnEnterDoor += EnterDoor;
		Player.gameObject.SetActive(false);

		EnemyMgr = new EnemyMgr();
		EnemyMgr.Init();

		SelectLevel(0);

		EventMgr.Ins.RegistEvent(GameState.GameEnd, EndGame);
	}

	public void StartGame()
	{
		SoundMgr.Ins.PlayBg();
		MapGenerate.GenerateMap(Row, Col);
		AStarGridMgr.GenerateGrid(Row, Col);

		GeneratePlayer();
		EnemyMgr.GenerateEnemies(CurLevelInfo.EnemyList.Count);
//		EnemyMgr.OnEnemeyClear += GameWin;
	}

	public void SelectNextLeve(Action<bool> action)
	{
		if (GameInfo.Contains(LevelID + 1))
		{
			LevelID++;
			SelectLevel(LevelID);
			Reset();
			StartGame();

			if (action != null) {
				action(true);
			}
		}
		else
		{
			if (action != null)
			{
				action(false);
			}
		}
	}

	void SelectLevel(int levelID) {
		LevelID = levelID;
		CurLevelInfo = GameInfo[LevelID];

		Row = CurLevelInfo.Row;
		Col = CurLevelInfo.Col;
	}

	public void RestartGame()
	{
		Reset();
		Player.Data.Reset();
		StartGame();
	}

	private void GeneratePlayer()
	{
		Player.gameObject.SetActive(true);
		Player.Born();
	}

	void EnterDoor()
	{
		if (EnemyMgr.CurEnemyCount == 0)
		{
			if (!IsGameEnd)
			{
				EndGame();
				EventMgr.Ins.RaiseEvent(GameState.GameEnd, new object[] { true });
			}
		}
	}

	private void EndGame(object[] args = null)
	{
		IsGameEnd = true;
		Player.Enable = false;
	}

	void Reset()
	{
		IsGameEnd = false;
		MapGenerate.Reset();
		AStarGridMgr.Reset();
		EnemyMgr.Reset();
		Player.Reset();
	}

	void Clear()
	{
		EnemyMgr.Clear();
	}
}
